package com.game.utils;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DataBaseUtil {
    private static final HikariDataSource dataSource;
    private static boolean isInitialized = false;

    static {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://47.120.7.56:3306/game");
        config.setUsername("game");
        config.setPassword("shannon");
        config.setDriverClassName("com.mysql.cj.jdbc.Driver");
        config.setMaximumPoolSize(10); // 根据需要调整最大连接数
        config.setMinimumIdle(5);      // 根据需要调整最小空闲连接数
        config.setIdleTimeout(30000);  // 空闲超时时间
        config.setMaxLifetime(1800000); // 最大生命周期
        config.setConnectionTimeout(30000); // 连接超时时间

        dataSource = new HikariDataSource(config);
    }

    /**
     * 初始化数据库连接池并预热
     * 返回初始化是否成功
     */
    public static boolean initializeDatabase() {
        if (isInitialized) {
            return true;
        }

        try {
            // 预热连接池，创建最小空闲连接数量的连接
            System.out.println("正在初始化数据库连接池...");
            Connection[] connections = new Connection[5];
            for (int i = 0; i < 5; i++) {
                connections[i] = dataSource.getConnection();
            }
            
            // 验证连接是否有效
            for (Connection conn : connections) {
                if (conn != null && !conn.isClosed()) {
                    conn.close();
                }
            }
            
            isInitialized = true;
            System.out.println("数据库连接池初始化成功！");
            return true;
        } catch (SQLException e) {
            System.err.println("数据库连接池初始化失败：" + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    public static Connection getConnection() throws SQLException {
        System.out.println("尝试获取数据库连接...");
        Connection conn = dataSource.getConnection();
        if (conn != null) {
            System.out.println("成功连接数据库");
        }else {
            System.out.println("数据库连接失败");
        }
        return conn;
    }

    public static void closeDataSource() {
        if (dataSource != null && !dataSource.isClosed()) {
            dataSource.close();
        }
    }

    // 登录逻辑
    public static boolean validateUser(String username, String password) {
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();
            // 打印数据库结果
            if (rs.next()) {
                System.out.println("用户名: " + rs.getString("username"));
                System.out.println("密码: " + rs.getString("password"));
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 注册逻辑
    public static boolean registerUser(String username, String password) {
        String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
        System.out.println(sql);
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            int rowsAffected = pstmt.executeUpdate(); // 使用 executeUpdate() 方法
            if (rowsAffected > 0) {
                System.out.println("用户注册成功");
                return true;
            } else {
                System.out.println("用户注册失败");
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return false; // 发生异常时返回 false
        }
    }

    // 创建排行榜的分数
    public static boolean changeScore(String gameid,String gametime, String score) {
        String sql = "INSERT INTO charts (gameid, gametime, score) VALUES (?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, gameid);
            pstmt.setString(2, gametime);
            pstmt.setString(3, score);
            int rowsAffected = pstmt.executeUpdate(); // 使用 executeUpdate() 方法
            if (rowsAffected > 0) {
                System.out.println("成绩记录成功");
                return true;
            } else {
                System.out.println("成绩记录失败");
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return false; // 发生异常时返回 false
        }
    }
}
